package com.uzai.console.service.sop.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.User;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.RedPackStatusEnum;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.dto.takebal.redpacket.RedPacketQuery;
import com.uzai.console.dto.user.wechatuser.WechatUserQuery;
import com.uzai.console.dto.user.wxworkuser.WxworkUserQuery;
import com.uzai.console.entity.DeviceType;
import com.uzai.console.entity.RedPacket;
import com.uzai.console.entity.SopTask;
import com.uzai.console.entity.SopTaskAddInfo;
import com.uzai.console.entity.es.*;
import com.uzai.console.enums.SopTaskStatusEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.sop.SopTaskSyncService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.vo.sop.soptask.SopTaskQueryParaVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 清理僵尸粉任务
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class SopTaskSyncServiceImpl implements SopTaskSyncService {

    Logger logger = LoggerFactory.getLogger(SopTaskSyncServiceImpl.class);

    @Autowired
    private SopTaskMapper sopTaskMapper;
    @Autowired
    private SopTaskAddInfoMapper sopTaskAddInfoMapper;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private RedPacketMapper redPacketMapper;
    @Autowired
    private UserService userService;

    /**
     * 后台异步添加查券未下单任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sopTask
     * @return null
     */
    @Async("taskExecutor")
    public void addSopTaskByQueryNoOrder(SopTask sopTask){
        int now = DateUtil.getNowTime();
        //当前时间
        Integer queryTime = 0; //页面查询天数
        LocalDate now_localDate = LocalDate.now();
        int lastOrderTimeStart = 0;
        int lastOrderTimeEnd = 0;
        String deviceType = null;
        List<Long> deviceUniqueIdList = null;
        //查询条件
        if(StringUtils.isNotBlank(sopTask.getQueryPara())){
            SopTaskQueryParaVo sopTaskQueryParaVo = JSONObject.parseObject(sopTask.getQueryPara(), SopTaskQueryParaVo.class);
            if(sopTaskQueryParaVo != null){
                queryTime =  Tools.getInteger(sopTaskQueryParaVo.getQueryTime());
                if(queryTime > 0) { //查询多少天时下过订单的会员
                    //获取多少天之前的那天的日期
                    LocalDate localDateMinus = now_localDate.minusDays(sopTaskQueryParaVo.getQueryTime());
                    //获取那天的开始时间
                    LocalDateTime localDateTime_start = localDateMinus.atStartOfDay();
                    //获取那天的结束时间
                    LocalDateTime localDateTime_end = LocalDateTime.of(localDateMinus, LocalTime.MAX);
                    //LocalDateTime 转时间戳
                    lastOrderTimeStart = (int) (LocalDateTimeUtil.toEpochMilli(localDateTime_start) /1000);
                    //获取多少天之前的那天的结束时间
                    lastOrderTimeEnd = (int) (LocalDateTimeUtil.toEpochMilli(localDateTime_end) /1000);
                }
                deviceType = sopTaskQueryParaVo.getDeviceType();
                deviceUniqueIdList = sopTaskQueryParaVo.getDeviceUniqueIdList();
            }
        }

        if(StringUtils.isBlank(deviceType)){
            //个人微信
            wechatUserQueryNoOrderSop(sopTask, deviceUniqueIdList, queryTime, lastOrderTimeStart, lastOrderTimeEnd, now);
            //企业微信
            wxworkUserQueryNoOrderSop(sopTask, deviceUniqueIdList, queryTime, lastOrderTimeStart, lastOrderTimeEnd, now);
        }else{
            if(DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(deviceType)){ //个人微信
                wechatUserQueryNoOrderSop(sopTask, deviceUniqueIdList, queryTime, lastOrderTimeStart, lastOrderTimeEnd, now);
            }else if(DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(deviceType)){//企业微信
                wxworkUserQueryNoOrderSop(sopTask, deviceUniqueIdList, queryTime, lastOrderTimeStart, lastOrderTimeEnd, now);
            }
        }

        //将任务状态修改成进行中
        sopTask.setStatus(SopTaskStatusEnum.ADDING.getId());
        sopTaskMapper.updateById(sopTask);
    }

    //个人微信会员查券未下单
    public void wechatUserQueryNoOrderSop(SopTask sopTask, List<Long> deviceUniqueIdList, Integer queryTime, int lastOrderTimeStart, int lastOrderTimeEnd, int now){
        //批量保存文件对象(100条一次)
        List<SopTaskAddInfo> sopTaskAddInfoList = new ArrayList<>();
        //添加好友总数量
        WechatUserQuery wechatUserQuery = new WechatUserQuery();
        wechatUserQuery.setMerId(sopTask.getMerId());
        //当天下过单的会员
        if(queryTime> 0){
            wechatUserQuery.setLastOrderTimeStart(lastOrderTimeStart);
            wechatUserQuery.setLastOrderTimeEnd(lastOrderTimeEnd);
        }else{//
            wechatUserQuery.setLastOrderType(2); //从未下单
        }
        //免打扰时间
        Integer busyTimeInterval = sopTask.getBusyTimeInterval();
        //页面设置了免打扰时间(页面填写的是小时)
        if(busyTimeInterval != null){
            //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)= 现在时间-页面设置的免打扰时间
            Integer busyGroupSendMsgTime = now - busyTimeInterval * 3600 ;
            wechatUserQuery.setBusyGroupSendMsgTime(busyGroupSendMsgTime);
        }

        //查询总数
        Integer count = wechatUserMapper.findCount(wechatUserQuery);
        //每页个数
        int size = 10;
        if (Tools.getInteger(count) > 0) {
            int totalPage = count / size + 1; //总页数
            for (int i = totalPage; i > 0; i--) {
                //每个时间段分页查询，每页200个
                Page<WechatUser> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                if (wechatUserList != null && wechatUserList.size() > 0) {
                    for (WechatUser wechatUser : wechatUserList) {
                        try {
                            //查询会员扩展信息
                            String uzai_user_ext_info_id = DeviceTypeEnum.DT_PC_WECHAT.getKey() + "_" + wechatUser.getMerId() + "_" + wechatUser.getBizUserId();
                            String uzai_user_ext_info = merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wechatUser.getMerId());
                            //查询会员基本信息
                            Map<String, Object> dataMp_ext = elasticsearchUtil.searchDataById(merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wechatUser.getMerId()), uzai_user_ext_info_id, null);
                            EsUserExtInfo esUserExtInfo = JSONObject.parseObject(JSONObject.toJSONString(dataMp_ext), EsUserExtInfo.class);
                            if (esUserExtInfo != null) {
                                //最后查券时间是否在当天
                                int lastQueryTime = Tools.getInteger(esUserExtInfo.getLastQueryTime());
                                if (lastQueryTime > lastOrderTimeStart && lastQueryTime < lastOrderTimeEnd) {
                                    //查询是否已经存在,存在则不需要添加
                                    SopTaskAddInfo sopTaskAddInfo = sopTaskAddInfoMapper.selectByTaskIdAndWxid(sopTask.getId(), wechatUser.getId());
                                    if (sopTaskAddInfo != null) {
                                        continue;
                                    }
                                    sopTaskAddInfo = new SopTaskAddInfo();
                                    sopTaskAddInfo.setId(IdWorker.getId());
                                    sopTaskAddInfo.setMerId(sopTask.getMerId());
                                    sopTaskAddInfo.setTaskId(sopTask.getId());
                                    sopTaskAddInfo.setDeviceType(wechatUser.getDeviceType());
                                    sopTaskAddInfo.setDeviceUniqueId(wechatUser.getDeviceUniqueId());
                                    sopTaskAddInfo.setDataId(wechatUser.getId());
                                    sopTaskAddInfo.setWxid(wechatUser.getBizUserId());
                                    sopTaskAddInfo.setNick(wechatUser.getNickName());
                                    sopTaskAddInfo.setHimg(wechatUser.getHeadImg());
                                    sopTaskAddInfo.setQueryTime(esUserExtInfo.getLastQueryTime());
                                    sopTaskAddInfo.setOrderTime(wechatUser.getLastOrderTime());
                                    sopTaskAddInfo.setRedSendTime(null);
                                    sopTaskAddInfo.setCreateTime(now);
                                    sopTaskAddInfo.setUpdateTime(now);
                                    sopTaskAddInfoList.add(sopTaskAddInfo);
                                    //判断条数，如果条数大于100条，批量处理
                                    if (sopTaskAddInfoList.size() >= 100) {
                                        //去重复
                                        sopTaskAddInfoList = sopTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                                        //批量保存清理僵尸粉发送明细
                                        sopTaskAddInfoMapper.batchAdd(sopTaskAddInfoList);
                                        //清空数据列表
                                        sopTaskAddInfoList.clear();
                                    }
                                }
                            }
                        } catch (Exception e) {
                            logger.error("-------addSopTaskByQueryNoOrder is error userId={}, error={}", wechatUser.getId(), e.getMessage());
                        }
                    }
                }
            }

            //最后将剩余不足100条的记录，批量处理
            if (sopTaskAddInfoList.size() > 0) {
                //去重复
                sopTaskAddInfoList = sopTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                //批量保存清理僵尸粉发送明细
                sopTaskAddInfoMapper.batchAdd(sopTaskAddInfoList);
                //清空本次导出的数据列表
                sopTaskAddInfoList.clear();
            }
        }
    }

    //企业微信会员查券未下单
    public void wxworkUserQueryNoOrderSop(SopTask sopTask, List<Long> deviceUniqueIdList, Integer queryTime, int lastOrderTimeStart, int lastOrderTimeEnd, int now){
        //批量保存文件对象(100条一次)
        List<SopTaskAddInfo> sopTaskAddInfoList = new ArrayList<>();
        //添加好友总数量
        WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
        wxworkUserQuery.setMerId(sopTask.getMerId());
        //当天下过单的会员
        if(queryTime> 0){
            wxworkUserQuery.setLastOrderTimeStart(lastOrderTimeStart);
            wxworkUserQuery.setLastOrderTimeEnd(lastOrderTimeEnd);
        }else{//
            wxworkUserQuery.setLastOrderType(2); //从未下单
        }
        //免打扰时间
        Integer busyTimeInterval = sopTask.getBusyTimeInterval();
        //页面设置了免打扰时间(页面填写的是小时)
        if(busyTimeInterval != null){
            //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)= 现在时间-页面设置的免打扰时间
            Integer busyGroupSendMsgTime = now - busyTimeInterval * 3600 ;
            wxworkUserQuery.setBusyGroupSendMsgTime(busyGroupSendMsgTime);
        }

        //查询总数
        Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
        //每页个数
        int size = 10;
        if (Tools.getInteger(count) > 0) {
            int totalPage = count / size + 1; //总页数
            for (int i = totalPage; i > 0; i--) {
                //每个时间段分页查询，每页200个
                Page<WxworkUser> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(page, wxworkUserQuery);
                if (wxworkUserList != null && wxworkUserList.size() > 0) {
                    for (WxworkUser wxworkUser : wxworkUserList) {
                        try {
                            //查询会员扩展信息
                            String uzai_user_ext_info_id = DeviceTypeEnum.DT_WORK_WECHAT.getKey() + "_" + wxworkUser.getMerId() + "_" + wxworkUser.getBizUserId();
                            String uzai_user_ext_info = merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wxworkUser.getMerId());
                            //查询会员基本信息
                            Map<String, Object> dataMp_ext = elasticsearchUtil.searchDataById(merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wxworkUser.getMerId()), uzai_user_ext_info_id, null);
                            EsUserExtInfo esUserExtInfo = JSONObject.parseObject(JSONObject.toJSONString(dataMp_ext), EsUserExtInfo.class);
                            if (esUserExtInfo != null) {
                                //最后查券时间是否在当天
                                int lastQueryTime = Tools.getInteger(esUserExtInfo.getLastQueryTime());
                                if (lastQueryTime > lastOrderTimeStart && lastQueryTime < lastOrderTimeEnd) {
                                    //查询是否已经存在,存在则不需要添加
                                    SopTaskAddInfo sopTaskAddInfo = sopTaskAddInfoMapper.selectByTaskIdAndWxid(sopTask.getId(), wxworkUser.getId());
                                    if (sopTaskAddInfo != null) {
                                        continue;
                                    }
                                    sopTaskAddInfo = new SopTaskAddInfo();
                                    sopTaskAddInfo.setId(IdWorker.getId());
                                    sopTaskAddInfo.setMerId(sopTask.getMerId());
                                    sopTaskAddInfo.setTaskId(sopTask.getId());
                                    sopTaskAddInfo.setDeviceType(wxworkUser.getDeviceType());
                                    sopTaskAddInfo.setDeviceUniqueId(wxworkUser.getDeviceUniqueId());
                                    sopTaskAddInfo.setDataId(wxworkUser.getId());
                                    sopTaskAddInfo.setWxid(wxworkUser.getBizUserId());
                                    sopTaskAddInfo.setNick(wxworkUser.getNickName());
                                    sopTaskAddInfo.setHimg(wxworkUser.getHeadImg());
                                    sopTaskAddInfo.setQueryTime(esUserExtInfo.getLastQueryTime());
                                    sopTaskAddInfo.setOrderTime(wxworkUser.getLastOrderTime());
                                    sopTaskAddInfo.setRedSendTime(null);
                                    sopTaskAddInfo.setCreateTime(now);
                                    sopTaskAddInfo.setUpdateTime(now);
                                    sopTaskAddInfoList.add(sopTaskAddInfo);
                                    //判断条数，如果条数大于100条，批量处理
                                    if (sopTaskAddInfoList.size() >= 100) {
                                        //去重复
                                        sopTaskAddInfoList = sopTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                                        //批量保存清理僵尸粉发送明细
                                        sopTaskAddInfoMapper.batchAdd(sopTaskAddInfoList);
                                        //清空数据列表
                                        sopTaskAddInfoList.clear();
                                    }
                                }
                            }
                        } catch (Exception e) {
                            logger.error("-------addSopTaskByQueryNoOrder is error userId={}, error={}", wxworkUser.getId(), e.getMessage());
                        }
                    }
                }
            }

            //最后将剩余不足100条的记录，批量处理
            if (sopTaskAddInfoList.size() > 0) {
                //去重复
                sopTaskAddInfoList = sopTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                //批量保存发送明细
                sopTaskAddInfoMapper.batchAdd(sopTaskAddInfoList);
                //清空本次导出的数据列表
                sopTaskAddInfoList.clear();
            }
        }
    }

    /**
     * 后台异步添加未下单任务添加明细
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sopTask
     * @return null
     */
    @Async("taskExecutor")
    public void addSopTaskByNoOrder(SopTask sopTask){
        int now = DateUtil.getNowTime();
        //当前时间
        Integer queryTime = 0; //页面查询天数
        LocalDate now_localDate = LocalDate.now();
        int lastOrderTimeStart = 0;
        int lastOrderTimeEnd = 0;
        String deviceType = null;
        List<Long> deviceUniqueIdList = null;
        //查询条件
        if(StringUtils.isNotBlank(sopTask.getQueryPara())){
            SopTaskQueryParaVo sopTaskQueryParaVo = JSONObject.parseObject(sopTask.getQueryPara(), SopTaskQueryParaVo.class);
            if(sopTaskQueryParaVo != null){
                queryTime =  Tools.getInteger(sopTaskQueryParaVo.getQueryTime());
                if(queryTime > 0){ //查询多少天时下过订单的会员
                    //获取多少天之前的那天的日期
                    LocalDate localDateMinus = now_localDate.minusDays(sopTaskQueryParaVo.getQueryTime());
                    //获取那天的开始时间
                    LocalDateTime localDateTime_start = localDateMinus.atStartOfDay();
                    //获取那天的结束时间
                    LocalDateTime localDateTime_end = LocalDateTime.of(localDateMinus, LocalTime.MAX);
                    //LocalDateTime 转时间戳
                    lastOrderTimeStart = (int) (LocalDateTimeUtil.toEpochMilli(localDateTime_start) /1000);
                    //获取多少天之前的那天的结束时间
                    lastOrderTimeEnd = (int) (LocalDateTimeUtil.toEpochMilli(localDateTime_end) /1000);
                }

                deviceType = sopTaskQueryParaVo.getDeviceType();
                deviceUniqueIdList = sopTaskQueryParaVo.getDeviceUniqueIdList();
            }
        }

        logger.info("----sop查询时间startTime="+ lastOrderTimeStart +"; endTime=" + lastOrderTimeEnd);
        if(StringUtils.isBlank(deviceType)){
            //个人微信
            wechatUserNoOrderSop(sopTask, deviceUniqueIdList, queryTime, lastOrderTimeStart, lastOrderTimeEnd, now);
            //企业微信
            wxworkUserNoOrderSop(sopTask, deviceUniqueIdList, queryTime, lastOrderTimeStart, lastOrderTimeEnd, now);
        }else{
            if(DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(deviceType)){ //个人微信
                wechatUserNoOrderSop(sopTask, deviceUniqueIdList, queryTime, lastOrderTimeStart, lastOrderTimeEnd, now);
            }else if(DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(deviceType)){//企业微信
                wxworkUserNoOrderSop(sopTask, deviceUniqueIdList, queryTime, lastOrderTimeStart, lastOrderTimeEnd, now);
            }
        }

        //将任务状态修改成进行中
        sopTask.setStatus(SopTaskStatusEnum.ADDING.getId());
        sopTaskMapper.updateById(sopTask);
    }

    //处理个人微信会员未下单SOP任务
    public void wechatUserNoOrderSop(SopTask sopTask, List<Long> deviceUniqueIdList, Integer queryTime, int lastOrderTimeStart, int lastOrderTimeEnd, int now){

        //批量保存文件对象(100条一次)
        List<SopTaskAddInfo> sopTaskAddInfoList = new ArrayList<>();
        //添加好友总数量
        WechatUserQuery wechatUserQuery = new WechatUserQuery();
        wechatUserQuery.setMerId(sopTask.getMerId());
        wechatUserQuery.setDeviceUniqueIdList(deviceUniqueIdList);
        //当天下过单的会员
        if(queryTime> 0){
            wechatUserQuery.setLastOrderTimeStart(lastOrderTimeStart);
            wechatUserQuery.setLastOrderTimeEnd(lastOrderTimeEnd);
        }else{//
            wechatUserQuery.setLastOrderType(2); //从未下单
        }

        //免打扰时间
        Integer busyTimeInterval = sopTask.getBusyTimeInterval();
        //页面设置了免打扰时间(页面填写的是小时)
        if(busyTimeInterval != null){
            //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)= 现在时间-页面设置的免打扰时间
            Integer busyGroupSendMsgTime = now - busyTimeInterval * 3600 ;
            wechatUserQuery.setBusyGroupSendMsgTime(busyGroupSendMsgTime);
        }

        //查询总数
        Integer count = wechatUserMapper.findCount(wechatUserQuery);

        logger.info("----sop任务总数="+ count);

        //每页个数
        int size = 10;
        if (Tools.getInteger(count) > 0) {
            int totalPage = count / size + 1; //总页数
            for (int i = totalPage; i > 0; i--) {
                //每个时间段分页查询，每页200个
                Page<WechatUser> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                if (wechatUserList != null && wechatUserList.size() > 0) {
                    for (WechatUser wechatUser : wechatUserList) {
                        try {
                            //查询是否已经存在,存在则不需要添加
                            SopTaskAddInfo sopTaskAddInfo = sopTaskAddInfoMapper.selectByTaskIdAndWxid(sopTask.getId(), wechatUser.getId());
                            if (sopTaskAddInfo != null) {
                                continue;
                            }

                            //是否在私有黑名单当中
                            String id_blacklistPrv = wechatUserQuery.getMerId() + "_" + wechatUser.getBizUserId();
                            Map<String,Object> prv_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id_blacklistPrv, null);
                            if(prv_map != null){ //在私有黑名单当中
                                continue;
                            }

                            //是否在全网黑名单当中
                            String id_blacklistPub = wechatUser.getBizUserId();
                            Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, id_blacklistPub, null);
                            if(pub_map != null){//在全网黑名单中，需要判断是否在白名单中，
                                //是否在白名单当中
                                String id_white = wechatUserQuery.getMerId() + "_" + wechatUser.getBizUserId();
                                Map<String,Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, id_white, null);
                                if(white_map == null){ //在全网黑名单中，但是又不在白名单中
                                    continue;
                                }
                            }

                            sopTaskAddInfo = new SopTaskAddInfo();
                            sopTaskAddInfo.setId(IdWorker.getId());
                            sopTaskAddInfo.setMerId(sopTask.getMerId());
                            sopTaskAddInfo.setTaskId(sopTask.getId());
                            sopTaskAddInfo.setDeviceType(wechatUser.getDeviceType());
                            sopTaskAddInfo.setDeviceUniqueId(wechatUser.getDeviceUniqueId());
                            sopTaskAddInfo.setDataId(wechatUser.getId());
                            sopTaskAddInfo.setWxid(wechatUser.getBizUserId());
                            sopTaskAddInfo.setNick(wechatUser.getNickName());
                            sopTaskAddInfo.setHimg(wechatUser.getHeadImg());
                            sopTaskAddInfo.setQueryTime(null);
                            sopTaskAddInfo.setOrderTime(wechatUser.getLastOrderTime());
                            sopTaskAddInfo.setRedSendTime(null);
                            sopTaskAddInfo.setCreateTime(now);
                            sopTaskAddInfo.setUpdateTime(now);
                            sopTaskAddInfoList.add(sopTaskAddInfo);
                            //判断条数，如果条数大于100条，批量处理
                            if (sopTaskAddInfoList.size() >= 100) {
                                //去重复
                                sopTaskAddInfoList = sopTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                                //批量保存清理僵尸粉发送明细
                                sopTaskAddInfoMapper.batchAdd(sopTaskAddInfoList);

                                logger.info("----sop批量插入数量="+ sopTaskAddInfoList.size());

                                //清空数据列表
                                sopTaskAddInfoList.clear();
                            }
                        } catch (Exception e) {
                            logger.error("-------addSopTaskByQueryNoOrder is error userId={}, error={}", wechatUser.getId(), e.getMessage());
                        }
                    }
                }
            }

            //最后将剩余不足100条的记录，批量处理
            if (sopTaskAddInfoList.size() > 0) {
                //去重复
                sopTaskAddInfoList = sopTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                //批量保存清理僵尸粉发送明细
                sopTaskAddInfoMapper.batchAdd(sopTaskAddInfoList);

                logger.info("----sop批量插入数量="+ sopTaskAddInfoList.size());

                //清空本次导出的数据列表
                sopTaskAddInfoList.clear();
            }
        }
    }

    //处理企业微信会员未下单SOP任务
    public void wxworkUserNoOrderSop(SopTask sopTask, List<Long> deviceUniqueIdList, Integer queryTime, int lastOrderTimeStart, int lastOrderTimeEnd, int now){
        //批量保存文件对象(100条一次)
        List<SopTaskAddInfo> sopTaskAddInfoList = new ArrayList<>();
        //添加好友总数量
        WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
        wxworkUserQuery.setMerId(sopTask.getMerId());
        wxworkUserQuery.setDeviceUniqueIdList(deviceUniqueIdList);
        wxworkUserQuery.setLastOrderType(0);//未下单
        //当天下过单的会员
        if(queryTime> 0){
            wxworkUserQuery.setLastOrderTimeStart(lastOrderTimeStart);
            wxworkUserQuery.setLastOrderTimeEnd(lastOrderTimeEnd);
        }else{//
            wxworkUserQuery.setLastOrderType(2); //从未下单
        }

        //免打扰时间
        Integer busyTimeInterval = sopTask.getBusyTimeInterval();
        //页面设置了免打扰时间(页面填写的是小时)
        if(busyTimeInterval != null){
            //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)= 现在时间-页面设置的免打扰时间
            Integer busyGroupSendMsgTime = now - busyTimeInterval * 3600 ;
            wxworkUserQuery.setBusyGroupSendMsgTime(busyGroupSendMsgTime);
        }

        //查询总数
        Integer count = wxworkUserMapper.findCount(wxworkUserQuery);

        logger.info("----sop任务总数="+ count);

        //每页个数
        int size = 10;
        if (Tools.getInteger(count) > 0) {
            int totalPage = count / size + 1; //总页数
            for (int i = totalPage; i > 0; i--) {
                //每个时间段分页查询，每页200个
                Page<WxworkUser> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(page, wxworkUserQuery);
                if (wxworkUserList != null && wxworkUserList.size() > 0) {
                    for (WxworkUser wxworkUser : wxworkUserList) {
                        try {
                            //查询是否已经存在,存在则不需要添加
                            SopTaskAddInfo sopTaskAddInfo = sopTaskAddInfoMapper.selectByTaskIdAndWxid(sopTask.getId(), wxworkUser.getId());
                            if (sopTaskAddInfo != null) {
                                continue;
                            }

                            //是否在私有黑名单
                            String id_blacklistPrv = wxworkUserQuery.getMerId() + "_" + wxworkUser.getBizUserId();
                            Map<String,Object> prv_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id_blacklistPrv, null);
                            if(prv_map != null){ //在私有黑名单当中
                                continue;
                            }

                            //是否在全网黑名单当中
                            String id_blacklistPub = wxworkUser.getBizUserId();
                            Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, id_blacklistPub, null);
                            if(pub_map != null){//在全网黑名单当中，还得判断是否是在白名单当中
                                //是否在白名单当中
                                String id_white = wxworkUserQuery.getMerId() + "_" + wxworkUser.getBizUserId();
                                Map<String,Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, id_white, null);
                                if(white_map == null){//在全网黑名单当中，但是不在白名单当中
                                    continue;
                                }
                            }

                            sopTaskAddInfo = new SopTaskAddInfo();
                            sopTaskAddInfo.setId(IdWorker.getId());
                            sopTaskAddInfo.setMerId(sopTask.getMerId());
                            sopTaskAddInfo.setTaskId(sopTask.getId());
                            sopTaskAddInfo.setDeviceType(wxworkUser.getDeviceType());
                            sopTaskAddInfo.setDeviceUniqueId(wxworkUser.getDeviceUniqueId());
                            sopTaskAddInfo.setDataId(wxworkUser.getId());
                            sopTaskAddInfo.setWxid(wxworkUser.getBizUserId());
                            sopTaskAddInfo.setNick(wxworkUser.getNickName());
                            sopTaskAddInfo.setHimg(wxworkUser.getHeadImg());
                            sopTaskAddInfo.setQueryTime(null);
                            sopTaskAddInfo.setOrderTime(wxworkUser.getLastOrderTime());
                            sopTaskAddInfo.setRedSendTime(null);
                            sopTaskAddInfo.setCreateTime(now);
                            sopTaskAddInfo.setUpdateTime(now);
                            sopTaskAddInfoList.add(sopTaskAddInfo);
                            //判断条数，如果条数大于100条，批量处理
                            if (sopTaskAddInfoList.size() >= 100) {
                                //去重复
                                sopTaskAddInfoList = sopTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                                //批量保存清理僵尸粉发送明细
                                sopTaskAddInfoMapper.batchAdd(sopTaskAddInfoList);

                                logger.info("----sop批量插入数量="+ sopTaskAddInfoList.size());

                                //清空数据列表
                                sopTaskAddInfoList.clear();
                            }
                        } catch (Exception e) {
                            logger.error("-------addSopTaskByQueryNoOrder is error userId={}, error={}", wxworkUser.getId(), e.getMessage());
                        }
                    }
                }
            }

            //最后将剩余不足100条的记录，批量处理
            if (sopTaskAddInfoList.size() > 0) {
                //去重复
                sopTaskAddInfoList = sopTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                //批量保存发送明细
                sopTaskAddInfoMapper.batchAdd(sopTaskAddInfoList);

                logger.info("----sop批量插入数量="+ sopTaskAddInfoList.size());

                //清空本次导出的数据列表
                sopTaskAddInfoList.clear();
            }
        }
    }


    /**
     * 后台异步添加红包未领取任务添加明细
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sopTask
     * @return null
     */
    @Async("taskExecutor")
    public void addSopTaskByRedNoReceive(SopTask sopTask){
        int now = DateUtil.getNowTime();

        //当前时间
        LocalDate now_localDate = LocalDate.now();
        int lastOrderTimeStart = 0;
        int lastOrderTimeEnd = 0;
        String deviceType = null;
        List<Long> deviceUniqueIdList = null;
        //查询条件
        if(StringUtils.isNotBlank(sopTask.getQueryPara())){
            SopTaskQueryParaVo sopTaskQueryParaVo = JSONObject.parseObject(sopTask.getQueryPara(), SopTaskQueryParaVo.class);
            if(sopTaskQueryParaVo != null){
                //获取多少天之前的那天的日期
                LocalDate localDateMinus = now_localDate.minusDays(sopTaskQueryParaVo.getQueryTime());
                //获取那天的开始时间
                LocalDateTime localDateTime_start = localDateMinus.atStartOfDay();
                //获取那天的结束时间
                LocalDateTime localDateTime_end = LocalDateTime.of(localDateMinus, LocalTime.MAX);
                //LocalDateTime 转时间戳
                lastOrderTimeStart = (int) (LocalDateTimeUtil.toEpochMilli(localDateTime_start) /1000);
                //获取多少天之前的那天的结束时间
                lastOrderTimeEnd = (int) (LocalDateTimeUtil.toEpochMilli(localDateTime_end) /1000);

                deviceType = sopTaskQueryParaVo.getDeviceType();
                deviceUniqueIdList = sopTaskQueryParaVo.getDeviceUniqueIdList();

            }
        }

        logger.info("----sop查询时间startTime="+ lastOrderTimeStart +"; endTime=" + lastOrderTimeEnd);

        //批量保存文件对象(100条一次)
        List<SopTaskAddInfo> sopTaskAddInfoList = new ArrayList<>();
        //查询红包
        RedPacketQuery redPacketQuery = new RedPacketQuery();
        redPacketQuery.setMerId(sopTask.getMerId());
        redPacketQuery.setStatus(RedPackStatusEnum.UNCLAIMED_VALUE);
        redPacketQuery.setCreateTimeStart(lastOrderTimeStart);
        //查询条件
        if(StringUtils.isNotBlank(sopTask.getQueryPara())){
            SopTaskQueryParaVo sopTaskQueryParaVo = JSONObject.parseObject(sopTask.getQueryPara(), SopTaskQueryParaVo.class);
            if(sopTaskQueryParaVo != null){
                redPacketQuery.setTypeList(sopTaskQueryParaVo.getRedPacketTypeList());
                redPacketQuery.setDeviceType(deviceType);
                redPacketQuery.setDeviceUniqueIdList(deviceUniqueIdList);
            }
        }

        //查询总数
        Integer count = redPacketMapper.findCount(redPacketQuery);

        logger.info("----sop任务总数="+ count);

        //每页个数
        int size = 10;
        if (Tools.getInteger(count) > 0) {
            int totalPage = count / size + 1; //总页数
            for (int i = totalPage; i > 0; i--) {
                //每个时间段分页查询，每页200个
                Page<RedPacket> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<RedPacket> redPacketList = redPacketMapper.findByList(page, redPacketQuery);
                if (redPacketList != null && redPacketList.size() > 0) {
                    for (RedPacket redPacket : redPacketList) {
                        try {
                            //排除群内红包
                            if(StringUtils.isBlank(redPacket.getWxGroupId())){
                                if(DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(redPacket.getDeviceType())){ //个人微信
                                    WechatUser wechatUser = wechatUserMapper.selectById(redPacket.getUserId(), redPacket.getMerId());
                                    if(wechatUser == null){
                                        continue;
                                    }

                                    //查询是否已经存在,存在则不需要添加
                                    SopTaskAddInfo sopTaskAddInfo = sopTaskAddInfoMapper.selectByTaskIdAndWxid(sopTask.getId(), wechatUser.getId());
                                    if (sopTaskAddInfo != null) {
                                        continue;
                                    }

                                    //是否在私有黑名单当中
                                    String id_blacklistPrv = redPacket.getMerId() + "_" + wechatUser.getBizUserId();
                                    Map<String,Object> prv_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id_blacklistPrv, null);
                                    if(prv_map != null){ //在私有黑名单当中
                                        continue;
                                    }

                                    //是否在全网黑名单当中
                                    String id_blacklistPub = wechatUser.getBizUserId();
                                    Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, id_blacklistPub, null);
                                    if(pub_map != null){//在全网黑名单中，需要判断是否在白名单中，
                                        //是否在白名单当中
                                        String id_white = redPacket.getMerId() + "_" + wechatUser.getBizUserId();
                                        Map<String,Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, id_white, null);
                                        if(white_map == null){ //在全网黑名单中，但是又不在白名单中
                                            continue;
                                        }
                                    }

                                }else if(DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(redPacket.getDeviceType())){//企业微信
                                    WxworkUser wxworkUser = wxworkUserMapper.selectById(redPacket.getUserId(), redPacket.getMerId());
                                    if(wxworkUser == null){
                                        continue;
                                    }

                                    //是否在私有黑名单
                                    String id_blacklistPrv = redPacket.getMerId() + "_" + wxworkUser.getBizUserId();
                                    Map<String,Object> prv_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id_blacklistPrv, null);
                                    if(prv_map != null){ //在私有黑名单当中
                                        continue;
                                    }

                                    //是否在全网黑名单当中
                                    String id_blacklistPub = wxworkUser.getBizUserId();
                                    Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, id_blacklistPub, null);
                                    if(pub_map != null){//在全网黑名单当中，还得判断是否是在白名单当中
                                        //是否在白名单当中
                                        String id_white = redPacket.getMerId() + "_" + wxworkUser.getBizUserId();
                                        Map<String,Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, id_white, null);
                                        if(white_map == null){//在全网黑名单当中，但是不在白名单当中
                                            continue;
                                        }
                                    }
                                }

                                //查询是否已经存在,存在则不需要添加
                                SopTaskAddInfo sopTaskAddInfo = sopTaskAddInfoMapper.selectByTaskIdAndWxid(sopTask.getId(), redPacket.getId());
                                if (sopTaskAddInfo != null) {
                                    continue;
                                }

                                sopTaskAddInfo = new SopTaskAddInfo();
                                sopTaskAddInfo.setId(IdWorker.getId());
                                sopTaskAddInfo.setMerId(sopTask.getMerId());
                                sopTaskAddInfo.setTaskId(sopTask.getId());
                                sopTaskAddInfo.setDeviceType(redPacket.getDeviceType());
                                sopTaskAddInfo.setDeviceUniqueId(redPacket.getDeviceUniqueId());
                                sopTaskAddInfo.setDataId(redPacket.getId());
                                //微信昵称
                                User user = userService.findUserInfo(redPacket.getUserId(), redPacket.getDeviceType(), redPacketQuery.getMerId());
                                if(user != null){
                                    sopTaskAddInfo.setNick(user.getNickName());
                                    sopTaskAddInfo.setHimg(user.getHeadImg());
                                    sopTaskAddInfo.setWxid(user.getBizUserId());
                                }
                                sopTaskAddInfo.setQueryTime(null);
                                sopTaskAddInfo.setOrderTime(null);
                                sopTaskAddInfo.setRedSendTime(redPacket.getCreateTime());
                                sopTaskAddInfo.setCreateTime(now);
                                sopTaskAddInfo.setUpdateTime(now);
                                sopTaskAddInfoList.add(sopTaskAddInfo);
                                //判断条数，如果条数大于100条，批量处理
                                if (sopTaskAddInfoList.size() >= 100) {
                                    //去重复
                                    sopTaskAddInfoList = sopTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                                    //批量保存清理僵尸粉发送明细
                                    sopTaskAddInfoMapper.batchAdd(sopTaskAddInfoList);

                                    logger.info("----sop批量插入数量="+ sopTaskAddInfoList.size());

                                    //清空数据列表
                                    sopTaskAddInfoList.clear();
                                }
                            }
                        } catch (Exception e) {
                            logger.error("-------addSopTaskByQueryNoOrder is error userId={}, error={}", redPacket.getId(), e.getMessage());
                        }
                    }
                }
            }

            //最后将剩余不足100条的记录，批量处理
            if (sopTaskAddInfoList.size() > 0) {
                //去重复
                sopTaskAddInfoList = sopTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                //批量保存清理僵尸粉发送明细
                sopTaskAddInfoMapper.batchAdd(sopTaskAddInfoList);

                logger.info("----sop批量插入数量="+ sopTaskAddInfoList.size());

                //清空本次导出的数据列表
                sopTaskAddInfoList.clear();
            }

        }

        //将任务状态修改成进行中
        sopTask.setStatus(SopTaskStatusEnum.ADDING.getId());
        sopTaskMapper.updateById(sopTask);
    }

}
